'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const destinationSchema = z.object({
  name: z.string().min(1, '请输入目的地名称'),
  description: z.string().optional(),
  imageUrl: z.string().optional(),
  metadata: z.object({
    location: z.string().min(1, '请输入位置信息'),
    bestTimeToVisit: z.string().min(1, '请输入最佳游览时间'),
    tips: z.string().min(1, '请输入温馨提示'),
    category: z.string().min(1, '请选择分类'),
  }),
  activities: z.array(z.object({
    title: z.string().min(1, '请输入活动标题'),
    description: z.string().optional(),
    duration: z.string().min(1, '请输入预计时长'),
  })),
});

type FormData = z.infer<typeof destinationSchema>;

type DestinationType = {
  id: string;
  name: string;
  description: string | null;
  imageUrl: string | null;
  metadata: {
    location: string;
    bestTimeToVisit: string;
    tips: string;
    category: string;
  } | null;
  activities: {
    id: string;
    title: string;
    description: string | null;
    metadata: {
      duration: string;
    } | null;
  }[];
};

interface DestinationFormProps {
  destination?: DestinationType;
}

export function DestinationForm({ destination }: DestinationFormProps) {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { register, handleSubmit, formState: { errors }, watch, setValue } = useForm<FormData>({
    resolver: zodResolver(destinationSchema),
    defaultValues: destination ? {
      name: destination.name,
      description: destination.description || '',
      imageUrl: destination.imageUrl || '',
      metadata: destination.metadata || {
        location: '',
        bestTimeToVisit: '',
        tips: '',
        category: '',
      },
      activities: destination.activities.map(activity => ({
        title: activity.title,
        description: activity.description || '',
        duration: activity.metadata?.duration || '',
      })),
    } : {
      name: '',
      description: '',
      imageUrl: '',
      metadata: {
        location: '',
        bestTimeToVisit: '',
        tips: '',
        category: '',
      },
      activities: [],
    },
  });

  const activities = watch('activities') || [];

  const onSubmit = async (formData: FormData) => {
    setIsSubmitting(true);
    setError(null);

    try {
      const response = await fetch(
        destination ? `/api/destinations/${destination.id}` : '/api/destinations',
        {
          method: destination ? 'PUT' : 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(formData),
        }
      );

      const responseData = await response.json();

      if (!response.ok) {
        throw new Error(responseData.error || '保存失败');
      }

      // 先刷新路由缓存
      router.refresh();
      
      // 等待一小段时间确保缓存已刷新
      await new Promise(resolve => setTimeout(resolve, 100));
      
      // 然后跳转
      router.push('/my-destinations');
    } catch (error) {
      console.error('Submit error:', error);
      setError(error instanceof Error ? error.message : '保存失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      {/* 基本信息 */}
      <div className="bg-white shadow sm:rounded-lg">
        <div className="px-4 py-5 sm:p-6">
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium leading-6 text-gray-900">基本信息</h3>
              <p className="mt-1 text-sm text-gray-500">设置目的地的基本信息</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700">目的地名称</label>
                <input
                  type="text"
                  {...register('name')}
                  placeholder="输入目的地名称"
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
                {errors.name && (
                  <p className="mt-2 text-sm text-red-600">{errors.name.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">描述</label>
                <textarea
                  {...register('description')}
                  rows={3}
                  placeholder="描述这个目的地的特色和亮点..."
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">图片链接</label>
                <input
                  type="text"
                  {...register('imageUrl')}
                  placeholder="输入图片URL地址"
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>
            </div>

            {error && (
              <div className="text-red-500 text-sm mt-2">
                {error}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 详细信息 */}
      <div className="bg-white shadow sm:rounded-lg">
        <div className="px-4 py-5 sm:p-6">
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium leading-6 text-gray-900">详细信息</h3>
              <p className="mt-1 text-sm text-gray-500">补充目的地的具体信息</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700">位置</label>
                <input
                  type="text"
                  {...register('metadata.location')}
                  placeholder="例如：北京市朝阳区..."
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
                {errors.metadata?.location && (
                  <p className="mt-2 text-sm text-red-600">{errors.metadata.location.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">最佳游览时间</label>
                <input
                  type="text"
                  {...register('metadata.bestTimeToVisit')}
                  placeholder="例如：春季3-5月..."
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
                {errors.metadata?.bestTimeToVisit && (
                  <p className="mt-2 text-sm text-red-600">{errors.metadata.bestTimeToVisit.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">温馨提示</label>
                <textarea
                  {...register('metadata.tips')}
                  rows={3}
                  placeholder="添加一些游览建议..."
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
                {errors.metadata?.tips && (
                  <p className="mt-2 text-sm text-red-600">{errors.metadata.tips.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">分类</label>
                <select
                  {...register('metadata.category')}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                >
                  <option value="" className="text-gray-500">请选择分类</option>
                  <option value="文化古迹">文化古迹</option>
                  <option value="自然风光">自然风光</option>
                  <option value="主题乐园">主题乐园</option>
                  <option value="城市观光">城市观光</option>
                  <option value="度假胜地">度假胜地</option>
                </select>
                {errors.metadata?.category && (
                  <p className="mt-2 text-sm text-red-600">{errors.metadata.category.message}</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 推荐活动 */}
      <div className="bg-white shadow sm:rounded-lg">
        <div className="px-4 py-5 sm:p-6">
          <div className="space-y-6">
            <div className="flex justify-between items-start">
              <div>
                <h3 className="text-lg font-medium leading-6 text-gray-900">推荐活动</h3>
                <p className="mt-1 text-sm text-gray-500">添加游览该目的地的推荐活动</p>
              </div>
              <button
                type="button"
                onClick={() => {
                  setValue('activities', [
                    ...activities,
                    { title: '', description: '', duration: '' }
                  ]);
                }}
                className="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
              >
                添加活动
              </button>
            </div>

            <div className="space-y-4">
              {activities.map((_, index) => (
                <div key={index} className="bg-gray-50 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-4">
                    <h4 className="text-sm font-medium text-gray-900">活动 {index + 1}</h4>
                    <button
                      type="button"
                      onClick={() => {
                        setValue(
                          'activities',
                          activities.filter((_, i) => i !== index)
                        );
                      }}
                      className="text-sm text-red-600 hover:text-red-500"
                    >
                      删除
                    </button>
                  </div>

                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">活动标题</label>
                      <input
                        type="text"
                        {...register(`activities.${index}.title`)}
                        placeholder="输入活动名称"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700">活动描述</label>
                      <textarea
                        {...register(`activities.${index}.description`)}
                        rows={2}
                        placeholder="描述活动内容..."
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700">预计时长</label>
                      <input
                        type="text"
                        {...register(`activities.${index}.duration`)}
                        placeholder="例如：2小时"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="flex justify-end space-x-4">
        <button
          type="button"
          onClick={() => router.back()}
          className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
          disabled={isSubmitting}
        >
          取消
        </button>
        <button
          type="submit"
          disabled={isSubmitting}
          className="px-4 py-2 text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
        >
          {isSubmitting ? '保存中...' : '保存'}
        </button>
      </div>
    </form>
  );
} 